// router.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/components/home.vue';
import DailyAnalysis from '@/components/dailyAnalysis.vue';
import ProvinceAnalysis from '@/components/provinceAnalysis.vue';
import ParkingStatus from '@/components/parkingStatus.vue';
import FeeCalculation from '@/components/feeCalculation.vue';
import Setting from '@/components/setting.vue';
import LoginView from '@/views/user/LoginView.vue';
import RegisterView from '@/views/user/RegisterView.vue';
import OffCar from '@/components/OffCar.vue';
import OffCarAbnormal from '@/components/OffCarAbnormal.vue';
// import store from '@/store/index';

const routes = [
  {
    path: "/home", // 移除末尾斜杠
    name: "home",
    component: Home, // 使用 PascalCase 命名
  },
  {
    path: "/dailyAnalysis",
    name: "dailyAnalysis",
    component: DailyAnalysis,
  },
  {
    path: "/provinceAnalysis",
    name: "provinceAnalysis",
    component: ProvinceAnalysis,
  },
  {
    path: "/parkingStatus",
    name: "parkingStatus",
    component: ParkingStatus,
  },
  {
    path: "/offcar",
    name: "offcar",
    component: OffCar,
  },
  {
    path: "/offcarabnormal",
    name: "offcarabnormal",
    component: OffCarAbnormal,
  },
  {
    path: "/feeCalculation",
    name: "feeCalculation",
    component: FeeCalculation,
  },
  {
    path: "/setting",
    name: "setting",
    component: Setting,
  },
  {
    path: "/login",
    name: "login",
    component: LoginView,
  },
  {
    path: "/register",
    name: "register",
    component: RegisterView,
  },
  {
    path: "/:catchAll(.*)",
    redirect: "/home",
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
// 全局前置守卫：拦截所有路由
router.beforeEach((to, from, next) => {
  // 获取登录状态和用户角色
  const isAuthenticated = !!localStorage.getItem("access_token");
  const userRole = JSON.parse(localStorage.getItem("user_info") || "{}").role;

  // 1. 登录/注册页面拦截：已登录用户禁止访问
  if (['login', 'register'].includes(to.name) && isAuthenticated) {
    next({ name: 'home' }); // 重定向到首页
    return;
  }

  // 2. 普通用户权限控制（非管理员禁止访问 feeCalculation 和 setting）
  const requiresAdmin = ['feeCalculation', 'setting'].includes(to.name);
  if (requiresAdmin && !isAuthenticated) {
    next({ name: 'login' }); // 未登录则跳转登录
    return;
  } else if (requiresAdmin && isAuthenticated && userRole !== 'admin') {
    next({ name: 'home' }); // 非管理员禁止访问，重定向首页
    return;
  }

  // 3. 其他页面：未登录用户跳转登录（除了公开页面）
  const publicPages = ['login', 'register']; // 可公开访问的页面
  if (!publicPages.includes(to.name) && !isAuthenticated) {
    next({ name: 'login' }); // 未登录且访问非公开页面，跳转登录
    return;
  }

  // 允许访问
  next();
});
export default router